<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card v-loading="Lodaing">
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button icon="el-icon-plus" size="small" type="primary" @click="clickShowAdd"
              >新增角色</el-button
            >
            <!-- 表格 -->
            <el-table :data="roleList">
              <el-table-column
                label="序号"
                width="100"
                type="index"
                align="right"
                :index="indexMethod"
              />
              <el-table-column label="角色名称" width="240" prop="name" align="right" />
              <el-table-column label="描述" prop="description" align="right" />
              <el-table-column #default="{ row }" label="操作" align="right">
                <el-button size="small" type="success" @click="allocationAuthority(row.id)"
                  >分配权限</el-button
                >
                <el-button size="small" type="primary" @click="editRole(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <!-- 1. current-page 标记当前页 (谁高亮)
              2. page-sizes 可供选择的每页条数列表
              3. page-size 起作用的每页条数
              4. layout 布局, 控制是展示的控件列表布局
              5. total 总条数
              @size-change="handleSizeChange" 每页条数变化
              @current-change="handleCurrentChange" 当前页变化
              -->
            <el-pagination
              :current-page="page"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pagesize"
              layout="total,   sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <!-- 公司信息 -->
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyData.name" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyData.companyAddress" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyData.mailbox" disabled style="width: 400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="companyData.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <addRole
        ref="addRole"
        :show-dialog.sync="showDialog"
        :node-data="nodeData"
        @add-role="fatherAddRole"
        @edit-role="getRoleList"
      />
      <!-- 分配权限的弹层 -->
      <el-dialog
        :close-on-click-modal="false"
        title="分配权限"
        :visible="showAssignDialog"
        @open="openDialog"
        @close="closeAssignDialog"
      >
        <!-- show-checkbox 表示节点是否可以被选择 -->
        <!-- check-strictly 父子节点不关联 -->
        <el-tree
          ref="tree"
          v-loading="isloading"
          node-key="id"
          default-expand-all
          check-strictly
          show-checkbox
          :data="jurisdictionTree"
          :props="{ label: 'name' }"
        />
        <template #footer>
          <div style="text-align: right">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="assignPerm">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRoleListApi, delRoleApi, getCompanyDataApi } from '@/api/role'
import addRole from '@/views/setting/components/addRole.vue'
import { mapGetters } from 'vuex'
import { jurisdictionListApi } from '@/api/permission'
import { findLeader } from '@/utils/index'
import { getRoleDetailsApi } from '@/api/role'
import { authorityOfDistributionApi } from '@/api/role'

export default {
  name: 'Setting',
  components: {
    addRole
  },
  data() {
    return {
      // el-tabs默认选中展示
      // activeName: 'first',
      // 当前页码数
      page: 1,
      // 当前页面需要的数据条数
      pagesize: 10,
      roleList: [],
      total: 0,
      Lodaing: false,
      // 弹框显示数据
      showDialog: false,
      // 向子组件传递的数据
      nodeData: {},
      companyData: {},
      showAssignDialog: false,
      roleId: '',
      jurisdictionTree: [],
      isloading: false
    }
  },
  created() {
    // 调用获取角色列表函数
    this.getRoleList()
    // 获取公司信息
    this.getCompanyData()
  },
  methods: {
    ...mapGetters(['companyId']),
    // 获取角色列表
    async getRoleList() {
      this.Lodaing = true
      const { data: res } = await getRoleListApi(this.page, this.pagesize)
      this.roleList = res.data.rows
      this.total = res.data.total
      this.Lodaing = false
    },
    // 每页条数变化
    handleSizeChange(val) {
      this.pagesize = val
      this.getRoleList()
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.page = val
      this.getRoleList()
    },
    // 计算序号
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 删除角色
    delRole(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await delRoleApi(id)
          this.$message.success('删除成功')
          // 如果这一页删完没内容了,就跳转到上一页
          if (this.roleList.length === 1 && this.page > 1) {
            this.page--
          }
          this.getRoleList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 添加角色
    clickShowAdd() {
      this.showDialog = true
      this.nodeData = ''
    },
    // 子组件通知父组件跳转页面刷新
    fatherAddRole() {
      this.page = Math.ceil((this.total + 1) / this.pagesize)
      this.getRoleList()
    },
    // 编辑角色
    async editRole(row) {
      this.showDialog = true
      this.nodeData = row
      this.$nextTick(() => {
        this.$refs.addRole.getRoleDetails()
      })
    },
    // 获取公司详情
    async getCompanyData() {
      const { data: res } = await getCompanyDataApi(this.companyId)
      // this.companyData = res.data
      console.log(res)
      this.companyData = {
        name: '阿伟有限公司',
        companyAddress: '天津市滨海新区胡家园街',
        remarks: '吃饭睡觉敲代码',
        mailbox: 'chenhaowei0527@163.com'
      }
    },
    // 打开弹窗时触发
    async openDialog() {
      this.isloading = true
      await this.jurisdictionList()
      await this.getRoleDetails()
      this.isloading = false
    },
    // 分配权限
    allocationAuthority(id) {
      this.roleId = id
      this.showAssignDialog = true
    },
    // 关闭分配权限的弹框
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    // 获取权限列表
    async jurisdictionList() {
      const { data: res } = await jurisdictionListApi()
      console.log(res)
      this.jurisdictionTree = findLeader(res.data, '0')
    },
    // 回显已有权限
    async getRoleDetails() {
      const {
        data: {
          data: { permIds }
        }
      } = await getRoleDetailsApi(this.roleId)
      console.log(permIds)
      this.$refs.tree.setCheckedKeys(permIds)
    },
    // 点击确定分配角色权限
    async assignPerm() {
      const permIds = this.$refs.tree.getCheckedKeys()
      authorityOfDistributionApi({ id: this.roleId, permIds })
        .then(res => {
          this.$message.success('修改权限成功')
          this.closeAssignDialog()
        })
        .catch(err => {
          console.log(err)
          this.$message.error('修改失败')
        })
    }
  }
}
</script>

<style>
.el-pagination {
  display: flex;
  justify-content: space-between;
}
</style>
